﻿using System.Net;
using System.Net.Security;
using Devonline.CloudService.Tencent.Weixin;
using Devonline.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;

namespace Devonline.CloudService.Tencent;

public static class ServiceExtensions
{
    /// <summary>
    /// 注册通用微信服务
    /// </summary>
    /// <param name="services"></param>
    /// <param name="endpoint"></param>
    /// <returns></returns>
    public static IServiceCollection AddWeixinService(this IServiceCollection services, IWeixinEndpoint? endpoint = default)
    {
        if (endpoint is not null)
        {
            services.AddSingleton(endpoint);
            services.AddHttpClient<WeixinService>(nameof(WeixinService), httpClient =>
            {
                if (endpoint.Protocol == ProtocolType.Https)
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((sender, cert, chain, errors) => true);
                }

                ArgumentNullException.ThrowIfNull(endpoint.Host);
                httpClient.BaseAddress = new Uri(endpoint.Host);
                httpClient.DefaultRequestHeaders.Add(HeaderNames.Accept, ContentType.Json);
            });

            services.AddScoped<IWeixinService, WeixinService>();
        }

        return services;
    }
}